package com.bright.ghj.user.cas;


import com.bright.ghj.user.manager.CommonUserManager;
import com.bright.ghj.user.pojo.dto.CommonUserDTO;
import com.bright.ghj.user.security.SecurityAuthority;
import com.bright.ghj.user.security.SecurityUser;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Set;

/**
 * @Author txf, hxj
 * @Date 2022/6/24 15:52
 * @Description
 */
//@Component
public abstract class AbstractCasUserDetailsService<T extends CommonUserDTO> implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {

    protected CommonUserManager<T> userManager;

    protected T getUserByToken(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
        String loginName = token.getName();
        return userManager.getUserByUserName(loginName);
    }


    protected abstract Set<SecurityAuthority> getAuthorities(T user);

    @Override
    public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
        return getUserDetails(token);
    }

    protected UserDetails getUserDetails(CasAssertionAuthenticationToken token) {

        T user = getUserByToken(token);

        user.setPassword(null);

        SecurityUser<T> securityUser = new SecurityUser<>();
        securityUser.setId(user.getId());
        securityUser.setUsername(user.getUserName());
        securityUser.setPassword(user.getPassword());
        securityUser.setUser(user);
        // TODO 初步设想是CommonUserDTO增加属性“权限” 权限的英文关键字用来给authority赋值
        securityUser.setSecurityAuthorities(getAuthorities(user));
        return securityUser;
    }
}
